package com.ifox.frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ifox.common.MyDefaultTableModel;
import com.ifox.entity.IFoxColumn;
import com.ifox.entity.IFoxTable;
import com.ifox.service.BaseService;

public class MappingFrame extends JDialog {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	private BaseService service = new BaseService();
	
	private static final long serialVersionUID = 3337575850556587038L;
	private JPanel contentPane;
	private JTextArea txtQueryLimit;
	private JTable tbColumnMapping;
	private JComboBox cmbSrcTable;
	private JComboBox cmbTargetTable;
	private JComboBox cmbStatusColumn;
	private JTable tbSrcPrimary;
	private JTable tbTargetPrimary;
	private JMenuItem mbtnAdd;
	private JMenuItem mbtnEdit;
	private JMenuItem mbtnDel;
	
	private String srcTable;
	private String targetTable;
	private Vector<String> srcColumns;
	private Vector<String> targetColumns;
	
	public MappingFrame(Dialog owner, boolean modal,String srcTable,String targetTable){
		super(owner, null, modal);
        addWindowListener(new WindowAdapter() {
        	@Override
        	public void windowOpened(WindowEvent e) {
        		initData();//初始化数据
        		if(StringUtils.isNotBlank(MappingFrame.this.srcTable) && StringUtils.isNotBlank(MappingFrame.this.targetTable)){
        			IFoxTable table = ListFrame.ifox.getTable(MappingFrame.this.srcTable, MappingFrame.this.targetTable);
            		cmbSrcTable.setSelectedItem(table.getSrcTable());
            		cmbSrcTable.setEnabled(false);
            		cmbTargetTable.setSelectedItem(table.getTargetTable());
            		cmbTargetTable.setEnabled(false);
            		cmbStatusColumn.setSelectedItem(table.getStatusColumn());
            		txtQueryLimit.setText(table.getQueryLimit());
            		for(int i=0;i<tbSrcPrimary.getRowCount();i++){
            			String value = tbSrcPrimary.getValueAt(i, 0).toString();
            			if(table.getSrcPrimary().contains(value)){
            				tbSrcPrimary.setRowSelectionInterval(i, i);
            			}
            		}
            		for(int i=0;i<tbTargetPrimary.getRowCount();i++){
            			String value = tbTargetPrimary.getValueAt(i, 0).toString();
            			if(table.getTargetPrimary().contains(value)){
            				tbTargetPrimary.setRowSelectionInterval(i, i);
            			}
            		}
        		}
        		refreshColumnMappingTable();
        	}
        });
		init();//初始化界面
		this.srcTable = srcTable;
		this.targetTable = targetTable;
	}
	
	private void init(){
		setModal(true);
		setResizable(false);
		setTitle("表映射管理");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 734, 545);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		contentPane.add(toolBar, BorderLayout.NORTH);
		
		JButton btnSave = new JButton("保存");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//验证
				String result = validSave();
				if(StringUtils.isNotBlank(result)){
					JOptionPane.showMessageDialog(null, result, "信息", JOptionPane.WARNING_MESSAGE);
				}else{
					//保存到ifox
					doSave();
					MappingFrame.this.dispose();
				}
			}
		});
		toolBar.add(btnSave);
		
		JButton btnClose = new JButton("关闭");
		btnClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MappingFrame.this.dispose();
			}
		});
		toolBar.add(btnClose);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(null);
		
		JPanel panel_1 = new JPanel();
		panel_1.setLayout(null);
		panel_1.setBorder(new TitledBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)), "\u8868\u6620\u5C04", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_1.setBounds(10, 5, 277, 196);
		panel.add(panel_1);
		
		JLabel label = new JLabel("发出表名：");
		label.setHorizontalAlignment(SwingConstants.RIGHT);
		label.setBounds(10, 29, 60, 15);
		panel_1.add(label);
		
		cmbSrcTable = new JComboBox();
		cmbSrcTable.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if(e.getStateChange()==ItemEvent.SELECTED && !"======请选择======".equals(e.getItem().toString())){ 
					try {
						srcColumns = service.getColumnsFromSrcTable(ListFrame.ifox, e.getItem().toString());
						cmbStatusColumn.setModel(new DefaultComboBoxModel(srcColumns));
						String[] header = { "发出表主键" };
						tbSrcPrimary.setModel(getTableModel(srcColumns,header));
					} catch (Exception e1) {
						logger.error(e1.getMessage(),e1);
						JOptionPane.showMessageDialog(null, e1.getMessage(), "信息", JOptionPane.WARNING_MESSAGE);
					}
              } 
			}
		});
		cmbSrcTable.setBounds(75, 26, 191, 21);
		panel_1.add(cmbSrcTable);
		
		cmbTargetTable = new JComboBox();
		cmbTargetTable.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if(e.getStateChange()==ItemEvent.SELECTED && !"======请选择======".equals(e.getItem().toString())){ 
					try {
						targetColumns = service.getColumnsFromTargetTable(ListFrame.ifox, e.getItem().toString());
						cmbStatusColumn.setModel(new DefaultComboBoxModel(targetColumns));
						String[] header = { "目标表主键" };
						tbTargetPrimary.setModel(getTableModel(targetColumns,header));
					} catch (Exception e1) {
						logger.error(e1.getMessage(),e1);
						JOptionPane.showMessageDialog(null, e1.getMessage(), "信息", JOptionPane.WARNING_MESSAGE);
					}
              } 
			}
		});
		cmbTargetTable.setBounds(75, 57, 191, 21);
		panel_1.add(cmbTargetTable);
		
		JLabel label_1 = new JLabel("目标表名：");
		label_1.setHorizontalAlignment(SwingConstants.RIGHT);
		label_1.setBounds(10, 60, 60, 15);
		panel_1.add(label_1);
		
		JLabel label_2 = new JLabel("状态列名：");
		label_2.setHorizontalAlignment(SwingConstants.RIGHT);
		label_2.setBounds(10, 91, 60, 15);
		panel_1.add(label_2);
		
		cmbStatusColumn = new JComboBox();
		cmbStatusColumn.setBounds(75, 88, 191, 21);
		panel_1.add(cmbStatusColumn);
		
		JLabel label_3 = new JLabel("查询限制：");
		label_3.setHorizontalAlignment(SwingConstants.RIGHT);
		label_3.setBounds(10, 119, 60, 15);
		panel_1.add(label_3);
		
		txtQueryLimit = new JTextArea();
		txtQueryLimit.setColumns(10);
		txtQueryLimit.setBounds(75, 116, 191, 68);
		panel_1.add(txtQueryLimit);
		
		JPanel panel_2 = new JPanel();
		panel_2.setLayout(null);
		panel_2.setBorder(new TitledBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)), "\u5217\u6620\u5C04", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_2.setBounds(10, 207, 707, 274);
		panel.add(panel_2);
		
		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(10, 24, 687, 240);
		panel_2.add(scrollPane_2);
		
		JPopupMenu popupMenu = new JPopupMenu();
		
		mbtnAdd = new JMenuItem("新增");
		mbtnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String result = validAddOrUpdate();
				if(StringUtils.isBlank(result)){
					ColumnMappingFrame frame = new ColumnMappingFrame(MappingFrame.this,true,srcColumns,targetColumns);
					frame.setLocationRelativeTo(null);
					frame.setVisible(true);
					addRow(frame.getiFoxCol());//添加表格数据
				}else{
					JOptionPane.showMessageDialog(null, result , "信息", JOptionPane.WARNING_MESSAGE);
				}
			}
		});
		mbtnAdd.setIcon(new ImageIcon(MappingFrame.class.getResource("/com/ifox/res/edit_add.png")));
		popupMenu.add(mbtnAdd);
		
		mbtnEdit = new JMenuItem("编辑");
		mbtnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int row = tbColumnMapping.getSelectedRow();
				String result = validAddOrUpdate();
				if(row<0){
					JOptionPane.showMessageDialog(null, "请先选中一行再使用该功能！" , "信息", JOptionPane.WARNING_MESSAGE);
				}else if(StringUtils.isNotBlank(result)){
					JOptionPane.showMessageDialog(null, result , "信息", JOptionPane.WARNING_MESSAGE);
				}else{
					ColumnMappingFrame frame = new ColumnMappingFrame(MappingFrame.this,true,srcColumns,targetColumns);
					frame.setiFoxCol(getIFoxColumnByRowIndex(row));
					frame.setLocationRelativeTo(null);
					frame.setVisible(true);
					editRow(frame.getiFoxCol(),row);//更新表格数据
				}
			}
		});
		mbtnEdit.setIcon(new ImageIcon(MappingFrame.class.getResource("/com/ifox/res/pencil.png")));
		popupMenu.add(mbtnEdit);
		
		mbtnDel = new JMenuItem("删除");
		mbtnDel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int rowIndex = tbColumnMapping.getSelectedRow();
				DefaultTableModel model = (DefaultTableModel)tbColumnMapping.getModel();
				model.removeRow(rowIndex);
			}
		});
		mbtnDel.setIcon(new ImageIcon(MappingFrame.class.getResource("/com/ifox/res/cancel.png")));
		popupMenu.add(mbtnDel);
		
		tbColumnMapping = new JTable();
		scrollPane_2.setViewportView(tbColumnMapping);
		
		addPopup(tbColumnMapping, popupMenu);
		addPopup(scrollPane_2, popupMenu);
		
		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new TitledBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)), "\u53D1\u51FA\u8868\u4E3B\u952E", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_3.setBounds(297, 5, 205, 196);
		panel.add(panel_3);
		panel_3.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panel_3.add(scrollPane, BorderLayout.CENTER);
		
		tbSrcPrimary = new JTable();
		tbSrcPrimary.setModel(new MyDefaultTableModel(new Object[][]{},new String[]{"发出表主键"}));
		scrollPane.setViewportView(tbSrcPrimary);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new TitledBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)), "\u76EE\u6807\u8868\u4E3B\u952E", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_4.setBounds(512, 5, 205, 196);
		panel.add(panel_4);
		panel_4.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane_1 = new JScrollPane();
		panel_4.add(scrollPane_1, BorderLayout.CENTER);
		
		tbTargetPrimary = new JTable();
		tbTargetPrimary.setModel(new MyDefaultTableModel(new Object[][]{},new String[]{"目标表主键"}));
		scrollPane_1.setViewportView(tbTargetPrimary);
	}
	
	private void initData(){
		try {
			Vector<String> srcTables = service.getSrcTable(ListFrame.ifox);
			Vector<String> targetTables = service.getTargetTable(ListFrame.ifox);
			cmbSrcTable.setModel(new DefaultComboBoxModel(srcTables));
			cmbTargetTable.setModel(new DefaultComboBoxModel(targetTables));
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			JOptionPane.showMessageDialog(null, "获取数据失败，请检查数据库连接配置", "信息", JOptionPane.INFORMATION_MESSAGE);
		}
	}
	
	private Vector<String> getHeader(String[] columnNames){
		Vector<String> header = new Vector<String>();
		for (int i = 0; i < columnNames.length; i++) {
			header.add(columnNames[i]);
		}
		return header;
	}
	
	private Vector<Vector<String>> getRow(Vector<String> rows){
		Vector<Vector<String>> row = new Vector<Vector<String>>();
		Vector<String> cell;
		for (String key : rows) {
			cell = new Vector<String>();
			cell.add(key);
			row.add(cell);
		}
		return row;
	}
	
	private TableModel getTableModel(Vector<String> rows,String[] columnNames){
		MyDefaultTableModel tablmod = new MyDefaultTableModel();
		tablmod.setDataVector(getRow(rows), getHeader(columnNames));
		return tablmod;
	}
	
	private void refreshColumnMappingTable(){
		tbColumnMapping.getTableHeader().setReorderingAllowed(false);
		tbColumnMapping.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

		tbColumnMapping.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		String[] header = {"发出表列名","发出表列类型","目标表列名","目标表列类型","直接复制","特殊值"};
		Object[][] rows = {};
		if(StringUtils.isNotBlank(srcTable) && StringUtils.isNotBlank(targetTable)){
			IFoxTable table = ListFrame.ifox.getTable(srcTable, targetTable);
			rows = new Object[table.getColumns().size()][6];
			for(int i=0;i<table.getColumns().size();i++){
				IFoxColumn c = table.getColumns().get(i);
				rows[i][0] = c.getSrcColumn();
				rows[i][1] = c.getSrcType();
				rows[i][2] = c.getTargetColumn();
				rows[i][3] = c.getTargetType();
				rows[i][4] = c.getDirectCopy();
				rows[i][5] = c.getSpecialValue();
			}
		}
		MyDefaultTableModel dtm = new MyDefaultTableModel(rows, header);
		tbColumnMapping.setModel(dtm);
		tbColumnMapping.getColumnModel().getColumn(0).setPreferredWidth(100);
		tbColumnMapping.getColumnModel().getColumn(1).setPreferredWidth(100);
		tbColumnMapping.getColumnModel().getColumn(2).setPreferredWidth(100);
		tbColumnMapping.getColumnModel().getColumn(3).setPreferredWidth(100);
		tbColumnMapping.getColumnModel().getColumn(5).setPreferredWidth(200);
	}
	
	public void addRow(IFoxColumn column){
		if(column!=null){
			DefaultTableModel dtm = (DefaultTableModel)tbColumnMapping.getModel();
			Vector<String> rowData = new Vector<String>();
			rowData.add(column.getSrcColumn());
			rowData.add(column.getSrcType());
			rowData.add(column.getTargetColumn());
			rowData.add(column.getTargetType());
			rowData.add(column.getDirectCopy());
			rowData.add(column.getSpecialValue());
			
			int rowIndex = isDataExist(column.getSrcColumn(),column.getTargetColumn());
			if(rowIndex>=0){
				JOptionPane.showMessageDialog(null, "该映射已存在！", "信息", JOptionPane.WARNING_MESSAGE);
				tbColumnMapping.setRowSelectionInterval(rowIndex, rowIndex);
			}else{
				dtm.addRow(rowData);
			}
		}
	}
	
	public int isDataExist(String src,String target){
		int flag = -1;
		int rowCount = tbColumnMapping.getRowCount();
		for(int i=0;i<rowCount;i++){
			String srcValue = tbColumnMapping.getValueAt(i, 0).toString();
			String targetValue = tbColumnMapping.getValueAt(i, 2).toString();
			if(src.equals(srcValue) && target.equals(targetValue)){
				flag = i;
				break;
			}
		}
		return flag;
	}
	
	public void editRow(IFoxColumn column,int rowIndex){
		if(column!=null){
			tbColumnMapping.setValueAt(column.getSrcColumn(), rowIndex, 0);
			tbColumnMapping.setValueAt(column.getSrcType(), rowIndex, 1);
			tbColumnMapping.setValueAt(column.getTargetColumn(), rowIndex, 2);
			tbColumnMapping.setValueAt(column.getTargetType(), rowIndex, 3);
			tbColumnMapping.setValueAt(column.getDirectCopy(), rowIndex, 4);
			tbColumnMapping.setValueAt(column.getSpecialValue(), rowIndex, 5);
		}
	}
	
	private void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				int row = tbColumnMapping.getSelectedRow();
				if(row<0){
					mbtnEdit.setEnabled(false);
					mbtnDel.setEnabled(false);
				}else{
					mbtnEdit.setEnabled(true);
					mbtnDel.setEnabled(true);
				}
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}

	public String getSrcTable() {
		return srcTable;
	}

	public void setSrcTable(String srcTable) {
		this.srcTable = srcTable;
	}

	public String getTargetTable() {
		return targetTable;
	}

	public void setTargetTable(String targetTable) {
		this.targetTable = targetTable;
	}
	
	public IFoxColumn getIFoxColumnByRowIndex(int index){
		IFoxColumn col = new IFoxColumn();
		col.setSrcColumn(tbColumnMapping.getValueAt(index, 0).toString());
		col.setSrcType(tbColumnMapping.getValueAt(index, 1).toString());
		col.setTargetColumn(tbColumnMapping.getValueAt(index, 2).toString());
		col.setTargetType(tbColumnMapping.getValueAt(index, 3).toString());
		col.setDirectCopy(tbColumnMapping.getValueAt(index, 4).toString());
		col.setSpecialValue(tbColumnMapping.getValueAt(index, 5).toString());
		return col;
	}
	
	private String validSave(){
		String result = "";
		if(cmbSrcTable.getSelectedIndex()==0){
			result += "请选择发出表名！\n";
		}
		if(cmbTargetTable.getSelectedIndex()==0){
			result += "请选择目标表名！\n";
		}
		if(cmbStatusColumn.getSelectedItem()==null || StringUtils.isBlank(cmbStatusColumn.getSelectedItem().toString())){
			result += "请选择状态列名！\n";
		}
		if(StringUtils.isBlank(txtQueryLimit.getText())){
			result += "查询限制不能为空！\n";
		}
		if(tbSrcPrimary.getSelectedRowCount()==0){
			result += "请选择发出表主键！\n";
		}
		if(tbTargetPrimary.getSelectedRowCount()==0){
			result += "请选择目标表主键！\n";
		}
		if(tbColumnMapping.getRowCount()==0){
			result += "请添加列映射规则！\n";
		}
		return result;
	}
	
	private String validAddOrUpdate(){
		String result = "";
		if(cmbSrcTable.getSelectedIndex()==0){
			result += "请选择发出表名！\n";
		}
		if(cmbTargetTable.getSelectedIndex()==0){
			result += "请选择目标表名！\n";
		}
		return result;
	}
	
	private void doSave(){
		IFoxTable table = new IFoxTable();
		List<String> srcPrimary = new ArrayList<String>();
		List<String> targetPrimary = new ArrayList<String>();
		List<IFoxColumn> columns = new ArrayList<IFoxColumn>();
		for(int i : tbSrcPrimary.getSelectedRows()){
			//发出表主键
			String value = tbSrcPrimary.getValueAt(i, 0).toString();
			srcPrimary.add(value);
		}
		
		for(int i : tbTargetPrimary.getSelectedRows()){
			//目标表主键
			String value = tbTargetPrimary.getValueAt(i, 0).toString();
			targetPrimary.add(value);
		}
		
		for(int i=0;i<tbColumnMapping.getRowCount();i++){
			IFoxColumn col = getIFoxColumnByRowIndex(i);
			columns.add(col);
		}
		table.setSrcTable(cmbSrcTable.getSelectedItem().toString());
		table.setTargetTable(cmbTargetTable.getSelectedItem().toString());
		table.setStatusColumn(cmbStatusColumn.getSelectedItem().toString());
		table.setQueryLimit(txtQueryLimit.getText());
		table.setSrcPrimary(srcPrimary);
		table.setTargetPrimary(targetPrimary);
		table.setColumns(columns);
		ListFrame.ifox.removeTable(cmbSrcTable.getSelectedItem().toString(), cmbTargetTable.getSelectedItem().toString());
		ListFrame.ifox.getTables().add(table);
	}
}

















